package com.szcinda.service.dto.idGenerator;

import com.szcinda.repository.IdGenerator;
import com.szcinda.repository.IdGeneratorRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.UUID;

@Service
@Transactional
public class IdGeneratorServiceImpl implements IdGeneratorService {
    private final IdGeneratorRepository idGeneratorRepository;

    public IdGeneratorServiceImpl(IdGeneratorRepository idGeneratorRepository) {
        this.idGeneratorRepository = idGeneratorRepository;
    }

    @Override
    public int getNextNumber(String tableName) {
        IdGenerator idGenerator = idGeneratorRepository.findByLocalDateAndTableName(LocalDate.now(), tableName);
        if (idGenerator == null) {
            idGenerator = new IdGenerator();
            idGenerator.setId(UUID.randomUUID().toString());
            idGenerator.setLocalDate(LocalDate.now());
            idGenerator.setTableName(tableName);
            idGenerator.setNumber(1);
            idGeneratorRepository.saveAndFlush(idGenerator);
            return 1;
        } else {
            idGenerator.setNumber(idGenerator.getNumber() + 1);
            idGeneratorRepository.saveAndFlush(idGenerator);
        }
        return idGenerator.getNumber();
    }
}
